<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: wsh
 * @Date: 2024-01-31 09:52:33
 * @LastEditors: wsh
 * @LastEditTime: 2024-02-01 16:07:24
-->
<template>
  <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="0">
    <el-form-item prop="originalPassword">
      <el-input v-model="ruleForm.originalPassword" type="password" placeholder="原密码" autocomplete="off" show-password />
    </el-form-item>

    <el-form-item prop="password">
      <el-input v-model="ruleForm.password" type="password" placeholder="8到16位同时包含大小写字母数字以及特殊符号的字符" autocomplete="off"
        show-password />
    </el-form-item>
    <el-form-item prop="confirmPassword">
      <el-input v-model="ruleForm.confirmPassword" type="password" placeholder="确认新密码" autocomplete="off" show-password />
    </el-form-item>

    <el-button type="primary" @click="submitForm(ruleFormRef)" class="w-100"> 修改密码 </el-button>
  </el-form>
</template>

<script lang="ts" setup>
import apiMod from '@/apiMod'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'

const ruleFormRef = ref<FormInstance>()

const emit = defineEmits(['refresh'])

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    const reg = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[\W]).{8,16}$/
    if (!reg.test(value)) {
      callback(new Error('密码必须为8到16位同时包含大小写字母数字以及特殊符号的字符'))
    } else if (ruleForm.confirmPassword !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== ruleForm.password) {
    callback(new Error('两次密码不一致!'))
  } else {
    callback()
  }
}

const ruleForm: any = reactive({
  password: '',
  confirmPassword: '',
  originalPassword: '',
})

const rules = reactive<any>({
  password: [{ validator: validatePass, trigger: 'blur' }],
  confirmPassword: [{ validator: validatePass2, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      apiMod.sys_user_changePwdSimple({ ...ruleForm }).then(res => {
        ElMessage.success(res.data)
        emit('refresh')
      })
    } else {
      return false
    }
  })
}

</script>
